package com.zfsn.okaria

import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import com.alibaba.android.arouter.facade.annotation.Route
import com.arialyy.annotations.Download
import com.arialyy.aria.core.Aria
import com.arialyy.aria.core.common.AbsEntity
import com.arialyy.aria.core.common.HttpOption
import com.arialyy.aria.core.download.DownloadEntity
import com.arialyy.aria.core.processor.IHttpFileLenAdapter
import com.arialyy.aria.core.task.DownloadTask
import com.arialyy.aria.util.ALog
import com.arialyy.aria.util.CommonUtil
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.Utils
import com.elvishew.xlog.XLog
import com.zfsn.okaria.databinding.PageSingleTaskLayoutBinding
import com.zfsn.okaria.viewbinding.BaseFragment
import com.zfsn.okaria.weight.ProgressLayout.OnProgressLayoutBtListener
import java.io.File

@Route(path = ARouteUtils.route_single_task)
class PageSingleTask : BaseFragment<PageSingleTaskLayoutBinding>(PageSingleTaskLayoutBinding::inflate) {
    private var mTaskId: Long = - 1
    private var mFilePath: String? = null
    private val HTTP_URL_KEY = "HTTP_URL_KEY"
    private val HTTP_PATH_KEY = "HTTP_PATH_KEY"
    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        Aria.download(this).register()
        val url =  "http://sf1-cdn-tos.huoshanstatic.com/obj/media-fe/xgplayer_doc_video/hls/xgplayer-demo.m3u8"
        //String url = "https://static.runoob.com/images/demo/demo2.jpg";
//        val filePath = "/mnt/sdcard/xxx.m3u8"
        val filePath = Utils.getApp().cacheDir.absolutePath + "/xxx.m3u8"
        FileUtils.createOrExistsFile(filePath)
        XLog.i("filePath:%s", filePath)
        var singDownloadInfo = Aria.download(context).getFirstDownloadEntity(url)
        if (singDownloadInfo == null) {
            singDownloadInfo = DownloadEntity()
            singDownloadInfo.setUrl(url)
            val file = File(filePath)
            singDownloadInfo.setFilePath(filePath)
            singDownloadInfo.setFileName(file.name)
        }else{
            SPUtils.getInstance().put(HTTP_PATH_KEY, singDownloadInfo.getFilePath())
            SPUtils.getInstance().put(HTTP_URL_KEY, singDownloadInfo.getUrl())
        }
        mTaskId = singDownloadInfo.getId();
        mUrl = singDownloadInfo.getUrl();
        mFilePath = singDownloadInfo.getFilePath();
        binding.idSingleTask.setInfo(singDownloadInfo);
        binding.idSingleTask.setBtListener(object :OnProgressLayoutBtListener{
            override fun create(v: View?, entity: AbsEntity?) {
                val option = HttpOption()
                option.useServerFileName(true)
                option.addHeader("1", "@").useServerFileName(true)
                    .setFileLenAdapter(object : IHttpFileLenAdapter {
                        override fun handleFileLen(headers: MutableMap<String, MutableList<String>>?): Long {
                            val sLength: List<String>? = headers?.get("Content-Length")
                            if (sLength == null || sLength.isEmpty()) {
                                return - 1
                            }
                            val temp = sLength[0]
                            return temp.toLong()
                        }
                    }) //option.setRequestType(RequestEnum.POST);
                //option.setRequestType(RequestEnum.POST);
                mTaskId = Aria.download(requireContext()).load(mUrl).setFilePath(mFilePath, true).option(option).ignoreCheckPermissions().create()
            }

            override fun stop(v: View?, entity: AbsEntity?) {
                Aria.download(this)
                    .load(mTaskId)
                    .stop();
            }

            override fun resume(v: View?, entity: AbsEntity?) {
                Aria.download(this).load(mTaskId)
                    //.updateUrl(mUrl)
                    .resume();
            }

            override fun cancel(v: View?, entity: AbsEntity?) {
                Aria.download(this).load(mTaskId).cancel(false);
            }
        })
    }
    override fun onDestroyView() {
        super.onDestroyView()
        Aria.download(this).unRegister()
    }
     var mUrl: String? = null
    @Download.onWait
    fun onWait(task: DownloadTask) {
        if (task.key == mUrl) {
            XLog.d(TAG, "wait ==> " + task.downloadEntity.fileName)
            binding.idSingleTask.setInfo(task.entity)
        }
    }

    @Download.onPre
    fun onPre(task: DownloadTask) {
        if (task.key == mUrl) {
            binding.idSingleTask.setInfo(task.entity)
        }
    }

    @Download.onTaskStart
    fun onTaskStart(task: DownloadTask) {
        if (task.key == mUrl) {
            binding.idSingleTask.setInfo(task.entity)
            ALog.d(TAG, "isComplete = " + task.isComplete + ", state = " + task.state)
        }
    }

    @Download.onTaskRunning
    fun onTaskRunning(task: DownloadTask) {
        if (task.key == mUrl) { //ALog.d(TAG, "isRunning" + "; state = " + task.getEntity().getState());
            XLog.d("下载速度：%s", task.convertSpeed)
            binding.idSingleTask.setInfo(task.entity)
        }
    }

    @Download.onTaskResume
    fun onTaskResume(task: DownloadTask) {
        if (task.key == mUrl) {
            ALog.d(TAG, "resume")
            binding.idSingleTask.setInfo(task.entity)
        }
    }

    @Download.onTaskStop
    fun onTaskStop(task: DownloadTask) {
        if (task.key == mUrl) {
            ALog.d(TAG, "stop")
            binding.idSingleTask.setInfo(task.entity)
        }
    }

    @Download.onTaskCancel
    fun onTaskCancel(task: DownloadTask) {
        if (task.key == mUrl) {
            mTaskId = - 1
            Log.d(TAG, "cancel")
            binding.idSingleTask.setInfo(task.entity)
        }
    }

    @Download.onTaskFail
    fun onTaskFail(task: DownloadTask?, e: Exception) {
        ALog.d(TAG, "下载失败  " + e.message)
        Toast.makeText(requireContext(), getString(R.string.download_fail), Toast.LENGTH_SHORT).show()
        if (task != null && task.key == mUrl) {
            binding.idSingleTask.setInfo(task.entity)
        }
    }

    @Download.onTaskComplete
    fun onTaskComplete(task: DownloadTask) {
        if (task.key == mUrl) {
            Toast.makeText(requireContext(), getString(R.string.download_success), Toast.LENGTH_SHORT).show() 
            //ALog.d(TAG, "文件md5: 9886e90f014d462b560dcec9c327bdb7");
            ALog.d(TAG, "下载完成的文件md5: " + CommonUtil.getFileMD5(File(task.filePath)) + " 文件路径：" + task.filePath)
            binding.idSingleTask.setInfo(task.entity)
            binding.idSingleTask.setProgress(100)
        }
    }
}